package com.ruoyi.system.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.token.TokenService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.dao.UserInfoDao;
import com.ruoyi.system.mapper.SyncSysUserMapper;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.mapper.UserInfoBpmMapper;
import com.ruoyi.system.mapper.UserInfoDingMapper;
import com.ruoyi.system.mapper.UserInfoEcMapper;
import com.ruoyi.system.mapper.UserInfoEmailMapper;
import com.ruoyi.system.mapper.UserInfoFinereportMapper;
import com.ruoyi.system.mapper.UserInfoGroupMapper;
import com.ruoyi.system.mapper.UserInfoIntegMapper;
import com.ruoyi.system.mapper.UserInfoLkMapper;
import com.ruoyi.system.mapper.UserInfoProjectMapper;
import com.ruoyi.system.mapper.UserInfoSchoolMapper;
import com.ruoyi.system.mapper.UserInfoTbMapper;
import com.ruoyi.system.mapper.UserInfoXiaoyuMapper;
import com.ruoyi.system.mapper.UserInfoXionganMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysHolderAccountService;
import com.ruoyi.system.service.ISysUserService;

import javax.annotation.Resource;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl implements ISysUserService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private SysPostMapper postMapper;

    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Resource
    private SysUserPostMapper userPostMapper;

    @Resource
    private ISysConfigService configService;

    @Resource
    private UserInfoDao userInfoDao;

    @Resource
    private ISysHolderAccountService sysHolderAccountService;

    @Resource
    private UserInfoXionganMapper userInfoXaMapper;

    @Resource
    private UserInfoXiaoyuMapper userInfoXiaoyuMapper;

    @Resource
    private UserInfoEcMapper userInfoEcMapper;

    @Resource
    private UserInfoBpmMapper userInfoBpmMapper;

    @Resource
    private UserInfoLkMapper userInfoLkMapper;

    @Resource
    private UserInfoTbMapper userInfoTbMapper;

    @Resource
    private UserInfoEmailMapper userInfoEmailMapper;

    @Resource
    private UserInfoSchoolMapper userInfoSchoolMapper;

    @Resource
    private UserInfoProjectMapper userInfoProjectMapper;

    @Resource
    private UserInfoIntegMapper userInfoIntegMapper;

    @Value("${interfaceAddress.ecSelectBpmAccountStatus}")
    private String ecUrl;


    @Value("${interfaceAddress.bpmUpdateAccountStatus}")
    private String bpmUrl;

    @Resource
    private SyncSysUserMapper syncSysUserMapper;

    @Resource
    private UserInfoFinereportMapper userInfoFinereportMapper;

    @Resource
    private UserInfoDingMapper userInfoDingMapper;

    @Resource
    private UserInfoGroupMapper userInfoGroupMapper;





    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user)
    {
        return userMapper.selectUserList(user);
    }

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllUserList(SysUser user)
    {
        return userMapper.selectAllUserList(user);
    }
    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName)
    {
        return userMapper.selectUserByUserName(userName);
    }


    @Override
    public String selectUserStatusByUserNo(String userNo) throws Exception {
        SysUser sysUser = userMapper.selectUserByUserNo(userNo);
        if (sysUser == null) {
          throw new Exception("user is null");
        }
        return  sysUser.getStatus();
    }

    /**
     * 通过用户ID查询用户
     *
     * @param Id 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long Id)
    {
        return userMapper.selectUserById(Id);
    }


    @Override
    public SysUser selectUserByUserId(String Id)
    {
        return userMapper.selectUserByUserId(Id);
    }
    /**
     * 通过用户ID查询用户---同一用户管理使用
     *
     * @param Id 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUnifyUserById(Long Id)
    {
        return userMapper.selectUnifyUserById(Id);
    }

    /**
     * 通过用户ID查询用户---同一用户查询使用
     *
     * @param Id 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUnifyUserByUserId(Long Id)
    {
        return userMapper.selectUnifyUserByUserId(Id);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName)
    {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list)
        {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName)
    {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list)
        {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName)
    {
        int count = userMapper.checkUserNameUnique(userName);
        if (count > 0)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public SysUser checkUserIdUnique(String userNo)
    {
        return userMapper.checkUserIdUnique(userNo);
    }


    @Override
    public SysUser checkUserIdCodeUnique(String userIdCode)
    {
        return userMapper.checkUserIdCodeUnique(userIdCode);
    }
    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user)
    {
        //todo test user id
        Long id = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        //todo test user id
        if (StringUtils.isNotNull(info) && info.getId().longValue() != id.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user)
    {
        //todo test user id
        Long id = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        //todo test user id
        if (StringUtils.isNotNull(info) && info.getId().longValue() != id.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user)
    {
        if (StringUtils.isNotNull(user.getId()) && user.isAdmin())
        {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user)
    {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        this.initUserAccountStatus(user);
        return rows;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user)
    {
        Long id = user.getId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(id);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(id);
        // 新增用户与岗位管理
        insertUserPost(user);
        int i = userMapper.updateUser(user);
        this.initUserAccountStatus(user);
        return i;
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar)
    {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password)
    {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles)
            {
                SysUserRole ur = new SysUserRole();
                //todo test user id
                ur.setUserId(user.getId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts)
            {
                SysUserPost up = new SysUserPost();
                //todo test user id
                up.setUserId(user.getId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0)
            {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param Id 用户ID
     * @return 结果
     */
    @Override
    public int deleteUserById(Long Id)
    {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(Id);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(Id);
        return userMapper.deleteUserById(Id);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    public int deleteUserByIds(Long[] userIds)
    {
        for (Long userId : userIds)
        {
            checkUserAllowed(new SysUser(userId));
        }
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 通过手机号查询用户
     * @param phonenumber 手机号
     * @return
     */
    @Override
    public List<SysUser> selectUserByPhonenumber(String phonenumber) {
        return userMapper.selectUserByPhonenumber(phonenumber);
    }

    @Override
    public int resetUserPwdByPhonenumber(SysUser sysUser) {
        return userMapper.resetUserPwdByPhonenumber(sysUser);
    }

	@Override
	public Map<String, Object> getUserInfoByJobNoOrPhone(SysUser sysUser) {
		Map<String, Object> resMap = new HashMap<String,Object>();
		SysUser userInfo = this.selectUnifyUserById(sysUser.getId());

		resMap.put("userInfo", userInfo);

		List<Map<String, Object>> resList = new ArrayList<Map<String,Object>>();
		//获取oa和经营的用户信息
		List<Map<String, Object>> OAUserInfoList = userInfoDao.getUserInfoList(sysUser.getUserNo());
		if(OAUserInfoList!=null && OAUserInfoList.size()>0) {
			resList.addAll(OAUserInfoList);
		}
		//获取bpm、ec、领款的用户信息-tb、企业培训学校、项目协同平台
		//获取域用户、阿里钉钉、Hr人力资源、帆软
		List<Map<String, Object>> otherUserInfoList =  userMapper.getUserInfoAllSystem(sysUser.getUserNo());
		if(otherUserInfoList!=null && otherUserInfoList.size()>0) {
			resList.addAll(otherUserInfoList);
		}

        //获取持有的域用户
        List<Map<String, Object>> groupHolderList = userInfoGroupMapper.selectUserInfoByGroupHolder(sysUser.getId());
        if(groupHolderList!=null && groupHolderList.size()>0) {
            resList.addAll(groupHolderList);
        }

        //获取持有的企业邮箱
        List<Map<String, Object>> emailHolderList = userInfoEmailMapper.selectUserInfoByEmailHolder(sysUser.getId());
        if(emailHolderList!=null && emailHolderList.size()>0) {
            resList.addAll(emailHolderList);
        }

		//获取小鱼视频、雄安协同平台的用户信息
		List<Map<String, Object>> otherUserInfoListByPhone =  userMapper.getUserInfoAllSystemByPhone(sysUser.getPhonenumber());
		if(otherUserInfoListByPhone!=null && otherUserInfoListByPhone.size()>0) {
			resList.addAll(otherUserInfoListByPhone);
		}

		//查询后台用户集成中用户信息
		List<Map<String, Object>> integListByUserId = userMapper.selectIntegerByUserId(sysUser.getId());
		if(integListByUserId!=null && integListByUserId.size()>0) {
			resList.addAll(integListByUserId);
		}


		if(resList!=null && resList.size()>0) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			for (Map<String, Object> map : resList) {
				if(map.get("lastLogonTime") !=null && StringUtils.isNotBlank(map.get("lastLogonTime").toString())) {
					System.out.println(map.get("lastLogonTime"));
					if("OA".equals(map.get("systemName").toString()) || "JY".equals(map.get("systemName").toString())) {
						map.put("lastLogonTime", sdf.format((Date)map.get("lastLogonTime")));
					}
					//System.out.println(sdf.format((Date)map.get("lastLogonTime")));
					//map.put("lastLogonTime", sdf.format((Date)map.get("lastLogonTime")));
				}else {
					map.put("lastLogonTime","");
				}
			}
		}
		resMap.put("otherSystem", resList);

		//查询本人下的所有代持信息
		List<SysHolderAccount> accounts = sysHolderAccountService.selectSysHolderAccountByUserId(sysUser.getId());
		List<Map<String, Object>> holderResList = new ArrayList<Map<String,Object>>();
		List<SysHolderAccount> errorList = new ArrayList<SysHolderAccount>();
		List<UserInfoInteg> integList = new ArrayList<UserInfoInteg>();
		integList = userInfoIntegMapper.selectIntegeHolderList(sysUser.getId().toString());


		if(accounts!=null && accounts.size()>0) {
			for (SysHolderAccount account : accounts) {
				if("OA".equals(account.getSystemName())) {
					List<Map<String, Object>> userInfoList = userInfoDao.getUserByAccountAndFlag(account.getAccount(),"OA");
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}else if("JY".equals(account.getSystemName())) {
					List<Map<String, Object>> userInfoList = userInfoDao.getUserByAccountAndFlag(account.getAccount(),"JY");
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}else if("BPM".equals(account.getSystemName())) {//获取bpm、ec、领款的用户信息-tb、企业邮箱、企业培训学校、项目协同平台
					List<Map<String, Object>> userInfoList =  userInfoBpmMapper.selectUserInfoBpmByJobNo(account.getAccount());
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}else if("EC".equals(account.getSystemName())) {
					List<Map<String, Object>> userInfoList =  userInfoEcMapper.selectUserInfoEcByJobNo(account.getAccount());
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}else if("LK".equals(account.getSystemName())) {
					List<Map<String, Object>> userInfoList =  userInfoLkMapper.selectUserInfoLkByJobNo(account.getAccount());
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}else if("tb".equals(account.getSystemName())) {
					List<Map<String, Object>> userInfoList =  userInfoTbMapper.selectUserInfoTbByJobNo(account.getAccount());
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}else if("email".equals(account.getSystemName())) {
					List<Map<String, Object>> userInfoList =  userInfoEmailMapper.selectUserInfoEmailByJobNo(account.getAccount());
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}else if("school".equals(account.getSystemName())) {
					List<Map<String, Object>> userInfoList =  userInfoSchoolMapper.selectUserInfoSchoolByJobNo(account.getAccount());
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}else if("project".equals(account.getSystemName())) {
					List<Map<String, Object>> userInfoList =  userInfoProjectMapper.selectUserInfoProjectByJobNo(account.getAccount());
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}else if("xiaoyu".equals(account.getSystemName())) {//获取小鱼视频、雄安协同平台的用户信息
					List<Map<String, Object>> userInfoList =  userInfoXiaoyuMapper.selectUserInfoXiaoyuByPhone(account.getAccount());
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}else if("xa".equals(account.getSystemName())) {
					List<Map<String, Object>> userInfoList =  userInfoXaMapper.selectUserInfoXaByPhone(account.getAccount());
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}//hr、帆软、阿里钉钉、域用户
				else if("HR".equals(account.getSystemName())) {
					List<Map<String, Object>> userInfoList =  syncSysUserMapper.selectUserInfoHRByJobNo(account.getAccount());
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}else if("FR".equals(account.getSystemName())) {
					List<Map<String, Object>> userInfoList =  userInfoFinereportMapper.selectUserInfoFRByJobNo(account.getAccount());
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}else if("ALDD".equals(account.getSystemName())) {
					List<Map<String, Object>> userInfoList =  userInfoDingMapper.selectUserInfoALDDByJobNo(account.getAccount());
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}else if("YYH".equals(account.getSystemName())) {
					List<Map<String, Object>> userInfoList =  userInfoGroupMapper.selectUserInfoYYHByJobNo(account.getAccount());
					if(userInfoList!=null && userInfoList.size()>0) {
						for (Map<String, Object> resUserInfo : userInfoList) {
							resUserInfo.put("account", account.getAccount());
							resUserInfo.put("remark", account.getRemark());
						}
						holderResList.addAll(userInfoList);
					}else {
						errorList.add(account);
					}
				}



			}
		}
		resMap.put("holderList", holderResList);
		resMap.put("errorList", errorList);
		resMap.put("integList", integList);
		return resMap;
	}


	@Override
	public List<SysUser> selectAllUser() {
		return userMapper.selectAllUser();
	}


    @Override
    public int updateUserForceFlag() {
        return userMapper.updateUserForceFlag();
    }

    @Override
    public int resigningStatus() {
        return userMapper.resigningStatus();
    }

    @Override
    public int updateCloseUserAccount() {
        return userMapper.updateCloseUserAccount();
    }

    @Override
    public void initUserAccountStatus(SysUser user) {
        String userNo = user.getUserNo();
        Date quitDate = user.getQuitDate();
        String incumbencyState = user.getIncumbencyState();
        String personnelType = user.getPersonnelType();
        SysUser sysUser = userMapper.selectUserByUserNo(userNo);
        String forceFlag = sysUser.getForceFlag();
        Date forceEndDate = sysUser.getForceEndDate();
        String competentOrg = user.getCompetentOrg();
        log.info("修改前用户信息：{} ,用户强制状态：{} ,预设强制时间：{} ,在职状态：{} , 离职日期：{}, 主管单位：{} , 人员类别: {} ,",userNo,forceFlag,forceEndDate,incumbencyState,quitDate,competentOrg,personnelType);
        String forceStatus = judgeForceFlag(forceFlag, forceEndDate);
        Map<String, String> stringStringMap = judgeUserStatus(incumbencyState, quitDate, personnelType, forceStatus, competentOrg);
        String status = stringStringMap.get("status");
        forceFlag = stringStringMap.get("forceFlag");
        log.info("修改后用户信息：{} ,用户状态: {},用户强制状态：{}",userNo,status,forceFlag);
        if ("0".equals(forceFlag)) {
            forceEndDate = null;
        }

        if (forceFlag == null) {
            forceFlag = "0";
            forceEndDate = null;
        }

        String origStatus = null;
        try {
            origStatus = this.selectUserStatusByUserNo(userNo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (status.equals(origStatus)) {
            log.info("现用户：{} 状态和原用户状态 '一样',不做处理 ,现状态： {} , 原状态： {} ",userNo, status, origStatus);
        } else {
            log.info("现用户：{} 状态与原用户状态 '不一样', 现状态： {} , 原状态： {}", userNo,status, origStatus);
//            if ("0".equals(status) || "2".equals(status) || "1".equals(forceFlag)) {
//                boolean bool = checkOutsideSystemStatus(userNo, true);
//                int update = bool ? updateTimingFlag(userNo, "1") : 0;
//            } else {
//                boolean bool = checkOutsideSystemStatus(userNo, false);
//                int update = bool ? updateTimingFlag(userNo, "2") : 0;
//            }
        }
        log.info("门户用户信息最终入参：{} ,用户状态: {},用户强制状态：{}, 用户预设关闭时间：{}",userNo,status,forceFlag,forceEndDate);
        //status => 门户用户信息  0启用 1离职待关闭 2从未开启 3离职停用
        userMapper.updateUserStatusByUserNo(userNo, status, forceFlag, forceEndDate);
        this.initHrUserAccountStatus(user);
    }

    @Override
    public void initHrUserAccountStatus(SysUser user) {
        String userNo = user.getUserNo();
        String incumbencyState = user.getIncumbencyState();
        String personnelType = user.getPersonnelType();
        String competentOrg = user.getCompetentOrg();
        String hrUserStatus = judgeHrStatus(personnelType, competentOrg, incumbencyState);
        //hrUserStatus => hr用户状态信息  0可用 1 不可用
        log.info("hr用户信息最终入参：{} ,用户状态: {} ,在职状态：{} , 主管单位：{} , 人员类别: {}",userNo,hrUserStatus,incumbencyState,competentOrg,personnelType);
        syncSysUserMapper.updateSyncSysUserStatusByEmpIdCode(hrUserStatus, userNo);
    }

    /**
     * 先处理开启，后处理关闭，顺序不可换，更新掉强制关闭的账户状态
     */
    @Override
    public void userStatusLinkage()
    {
        //  bpm : "state":Inactive(0),禁用 Active(1),启用
        // portal: 1 待开启 2 待关闭  3 已处理
//        List<String> userNoOpenList = userMapper.getUserStatusTimingFlag("1");

        /**
         * 先设置定时同步bpm状态为未处理
         */
        userMapper.setUserTimingFlag();

        List<String> portalUserOpen = userMapper.getPortalUserOpen();
        if (portalUserOpen != null && portalUserOpen.size() > 0) {
            StringBuffer openListStringBuffer = new StringBuffer();
            for (int i = 0; i < portalUserOpen.size(); i++) {
                String userNo = portalUserOpen.get(i);
                if (i == 0) {
                    openListStringBuffer.append(userNo);
                } else {
                    openListStringBuffer.append("," + userNo);
                }
            }
            Map<String, Object> openHashMap = new HashMap<>();
            openHashMap.put("userNoList",openListStringBuffer.toString());
            openHashMap.put("flag","1");
            String openJson = JSON.toJSONString(openHashMap);
            log.info("需要开启的bpm账号 ： {}",openListStringBuffer.toString());
            //帐号状态（1正常 2停用 3未启用）
            updateBpmUserStatus(openJson,portalUserOpen,"1");
        }


//        List<String> userNoCloseList = userMapper.getUserStatusTimingFlag("2");
        List<String> portalUserClose = userMapper.getPortalUserClose();
        if (portalUserClose != null && portalUserClose.size() > 0) {
            StringBuffer closeListStringBuffer = new StringBuffer();
            for (int i = 0; i < portalUserClose.size(); i++) {
                String userNo = portalUserClose.get(i);
                if (i == 0) {
                    closeListStringBuffer.append(userNo);
                } else {
                    closeListStringBuffer.append("," + userNo);
                }
            }
            Map<String, Object> closeHashMap = new HashMap<>();
            closeHashMap.put("userNoList",closeListStringBuffer.toString());
            closeHashMap.put("flag","0");
            String closeJson = JSON.toJSONString(closeHashMap);
            log.info("需要关闭的bpm账号 ： {}",closeListStringBuffer.toString());
            //帐号状态（1正常 2停用 3未启用）
            updateBpmUserStatus(closeJson,portalUserClose,"2");
        }

    }


    /**
     *
     * @param incumbencyState
     * @param quitDate
     * @param personnelType
     * @param forceFlag
     * @param competentOrg
     * @return
     */
    private Map<String, String> judgeUserStatus(String incumbencyState,Date quitDate,String personnelType,String forceFlag,String competentOrg){
        Map<String, String> stringStringHashMap = new HashMap<>(2);
        if (("01".equals(personnelType) || "02".equals(personnelType) || "03".equals(personnelType)) && "同济咨询".equals(competentOrg)) {
            stringStringHashMap = judgeInitUserStatus(incumbencyState, forceFlag, quitDate);
        } else {
            stringStringHashMap.put("status","1");
            stringStringHashMap.put("forceFlag",forceFlag);
        }
        return stringStringHashMap;
    }


    /**
     * 判断 是否到离职日期大于当天，如果大于 用户状态为离职停用 反之为 离职待关闭
     * @param quitDate
     * @return
     */
    private String judgeQuitDate(Date quitDate){
        /**
         * status: 0 启用 1 未开启 2 离职待关闭 3 离职停用
         */
        String status = null;
        if (quitDate != null) {
            boolean bool = DateUtils.timeCompare(DateUtils.getDate(), DateUtils.dateTime(quitDate));
            if (bool) {
                //离职待关闭
                status = "2";
            } else {
                //离职停用
                status = "3";
            }
        } else {
            status = "3";
        }
        log.info("判断离职日期后，离职状态为： {}",status);
        return status;
    }

    private Map<String, String> judgeInitUserStatus(String incumbencyState,String forceFlag,Date quitDate){
        /**
         * incumbencyState ：null ,01 在岗 ,02 无岗 , 03 离职 , 04 待入职 ,05 系统管理 , 06 数据作废
         * status: 0 启用 1 未开启 2 离职待关闭 3 离职停用
         */
        Map<String, String> stringStringHashMap = new HashMap<>();
        String status = null;
        if(incumbencyState!=null){
            switch (incumbencyState){

                /**
                 * 在岗 为 用户状态为 启用
                 */
                case "01":
                    stringStringHashMap.put("status","0");
                    stringStringHashMap.put("forceFlag",forceFlag);
                    break;

                /**
                 * 离职 需要判断 离职日期 超出离职日期为 离职待关闭 未超出为 离职停用
                  */
                case "03":
                    status = judgeQuitDate(quitDate);
                    stringStringHashMap.put("status",status);
                    stringStringHashMap.put("forceFlag",forceFlag);
                    break;
                /**
                 * 系统管理 用户状态 为 未开启 强制状态为 强制开启
                  */
                case "05":
                    stringStringHashMap.put("status","1");
                    if(forceFlag==null){
                        stringStringHashMap.put("forceFlag","1");
                    }else {
                        stringStringHashMap.put("forceFlag",forceFlag);
                    }
                    break;
                /**
                 * 其他 用户状态都为 未开启
                 */
                default:
                    stringStringHashMap.put("status","1");
                    stringStringHashMap.put("forceFlag",forceFlag);
            }
            /**
             * null 也为未开启
             */
        }else {
            stringStringHashMap.put("status","1");
            stringStringHashMap.put("forceFlag",forceFlag);
        }
        return stringStringHashMap;
    }

    private String judgeForceFlag(String forceFlag,Date forceEndDate){
        //强制开启
        String forceOpen = "1";
        if (forceOpen.equals(forceFlag) && forceEndDate!=null){
            boolean b = DateUtils.timeCompare(DateUtils.getDate(), DateUtils.dateTime(forceEndDate));
            if (!b){
                //取消强制
                forceFlag="0";
            }
        }
        return forceFlag;
    }


    private void updateBpmUserStatus(String json,List<String> userNoList,String bpmUserFlag){
        String returnStr = HttpUtils.doPost(bpmUrl, json);
        log.info("同步bpm账号状态,bpm返回结果：{}",returnStr);
        JSONObject jsonObject = JSON.parseObject(returnStr);
        Object code = jsonObject.get("code");
        int codeInt = Integer.parseInt(code.toString());
        if (HttpStatus.SUCCESS == codeInt){
            log.info("执行同步bpm状态成功");
            userMapper.updateTimingFlagBatch(userNoList,"2");
            userInfoBpmMapper.updateUserInfoBpmBatch(userNoList,bpmUserFlag);
        }else {
            log.info("执行同步bpm状态失败");
        }
    }

//    /**
//     * 处理定时标志 timingFlag 定时标志 1 待开启 2 待关闭  3 已处理
//     * @param userNo
//     * @param timingFlag
//     * @return
//     */
////    private int updateTimingFlag(String userNo,String timingFlag){
//        return userMapper.updateTimingFlag(userNo,timingFlag);
//    }

//    /**
//     * 检查外部系统联动（bpm/ec）
//     * 其他系统用户数据 1正常 2停用 3未启用
//     * @param userNo
//     * @return Boolean
//     */
//    private Boolean checkOutsideSystemStatus(String userNo ,Boolean userIsOpen){
//        Boolean checked = false;
//        String opening = "1";
//        UserInfoEc userInfoEc = userInfoEcMapper.selectUserInfoEcByOne(userNo);
//        UserInfoBpm userInfoBpm = userInfoBpmMapper.selectUserInfoBpmByOne(userNo);
//        if (userIsOpen) {
//            checked = checkOutsideSystemStatusBeOpen(userInfoBpm, opening);
//        } else {
//            checked = checkOutsideSystemStatusBeClose(userInfoEc, userInfoBpm, opening);
//        }
//        log.info("是否可修改bpm用户 checked：{}",checked);
//        return checked;
//    }

//    /**
//     * 判断是否需要开启 ，bpm开启 不需要再开启 ，bpm关闭 需要开启
//     * @param userInfoBpm
//     * @param opening
//     * @return
//     */
//    private Boolean checkOutsideSystemStatusBeOpen(UserInfoBpm userInfoBpm, String opening) {
//        boolean checked = false;
//        if (userInfoBpm == null) {
//            return false;
//        }
//        checked = !opening.equals(userInfoBpm.getUserStatus());
//        return checked;
//    }

//    /**
//     * 判断是否需要关闭 ec 开启 不需要关闭  ，ec 关闭时 ：bpm 开启 需要关闭，bpm关闭 不需要关闭
//     * @param userInfoEc
//     * @param userInfoBpm
//     * @param opening
//     * @return
//     */
//    private Boolean checkOutsideSystemStatusBeClose(UserInfoEc userInfoEc, UserInfoBpm userInfoBpm, String opening) {
//        boolean checked = false;
//        if (userInfoBpm == null) {
//            return false;
//        }
//        if (userInfoEc != null && opening.equals(userInfoEc.getUserStatus())) {
//            checked = false;
//        } else {
//            checked = opening.equals(userInfoBpm.getUserStatus());
//        }
//        return checked;
//    }

    private String judgeHrStatus(String personnelType,String competentOrg,String incumbencyState){
        String hrStatus = "";
        if (("01".equals(personnelType) || "02".equals(personnelType) || "03".equals(personnelType)) && "同济咨询".equals(competentOrg)) {
            hrStatus = judgeInitHrUserStatus(incumbencyState);
        } else {
            hrStatus = "1";
        }
        return hrStatus;
    }

    private String judgeInitHrUserStatus(String incumbencyState){
        /**
         * incumbencyState ：null ,01 在岗 ,02 无岗 , 03 离职 , 04 待入职 ,05 系统管理 , 06 数据作废
         * hrStatus: hr用户状态信息  0可用 1 不可用
         */

        String hrStatus = "";
        if(incumbencyState!=null){
            switch (incumbencyState){

                /**
                 * 在岗 系统管理 为 用户状态为 可用
                 */
                case "01":
                case "05":
                    hrStatus = "0";
                    break;
                /**
                 * 其他 用户状态都为 不可用
                 */
                default:
                    hrStatus = "1";
            }
            /**
             * null 也为未开启
             */
        }else {
            hrStatus = "1";
        }
        return hrStatus;
    }

	@Override
	@DataScope(deptAlias = "d", userAlias = "u")
	public List<SysUser> userListSearch(SysUser user) {
        return userMapper.userListSearch(user);
        }

    @Override
    public List<Map<String,Object>> checkedListSearch(Long[] ids) {
        return userMapper.checkedListSearch(ids);
    }

}
